package pl.edu.agh.io.gpstracker.client.widget;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import pl.edu.agh.io.gpstracker.client.action.DeleteUserAction;
import pl.edu.agh.io.gpstracker.client.action.FindAllUsersAction;
import pl.edu.agh.io.gpstracker.client.action.UpdateUserAction;
import pl.edu.agh.io.gpstracker.client.dto.UserDto;
import pl.edu.agh.io.gpstracker.client.result.CollectionResult;
import pl.edu.agh.io.gpstracker.client.result.VoidResult;
import pl.edu.agh.io.gpstracker.client.window.NewMessageWindow;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;

/**
 * 
 * @author wkedzior
 * 
 */
public class ManageUserWidget extends GenericWidget {

	private static final String PASSWORD = "password";
	private static final String TYPE = "type";
	private static final String LOGIN = "login";
	private static final String SURNAME = "surname";
	private static final String NAME = "name";
	private static final String ID2 = "id";
	private ListGrid userGrid;
	private IButton save;
	private IButton delete;
	private IButton sendMessage;
	private IButton refresh;

	public ManageUserWidget() {
	}

	@Override
	protected void onInit() {
		super.onInit();
		createWidget();
		loadUsers();
	}

	/**
	 * 
	 */
	private void createWidget() {
		userGrid = new ListGrid();
		// userGrid.setWidth(750);

		ListGridField id = new ListGridField("id", "Id");
		ListGridField password = new ListGridField(PASSWORD);
		ListGridField name = new ListGridField(NAME, "Imie");
		name.setCanEdit(true);
		name.setRequired(true);
		ListGridField surname = new ListGridField(SURNAME, "Nazwisko");
		surname.setCanEdit(true);
		surname.setRequired(true);
		ListGridField login = new ListGridField(LOGIN, "Login");
		login.setCanEdit(true);
		login.setRequired(true);
		ListGridField type = new ListGridField(TYPE, "Typ");
		LinkedHashMap<String, String> values = new LinkedHashMap<String, String>();
		values.put("0", "Uzytkownik mobilny");
		values.put("1", "Uzytkownik webowy");
		type.setValueMap(values);
		type.setCanEdit(true);

		userGrid.setFields(id,password, name, surname, login, type);

		HLayout bu = new HLayout();
		bu.setAlign(Alignment.RIGHT);
		save = new IButton("Zapisz");
		delete = new IButton("Usun");
		sendMessage = new IButton("Wyslij wiadomosc");
		sendMessage.setWidth(120);
		refresh = new IButton("Odswiez dane");

		save.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				updateUsers();
			}
		});
		delete.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (userGrid.getSelectedRecord() == null) {
					SC.warn("Nie wybrano rekordu!");
				} else {
					deleteUser();
				}
			}
		});

		sendMessage.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (userGrid.getSelectedRecord() == null) {
					SC.warn("Nie wybrano uzytkownika!");
				} else {
					sendMessage();
				}
			}
		});

		refresh.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				loadUsers();
			}
		});
		bu.setMargin(10);
		bu.setMembers(save, delete, sendMessage, refresh);
		bu.setMembersMargin(5);
		setMembers(userGrid, bu);
	}

	private void sendMessage() {
		new NewMessageWindow(createUserModel(userGrid.getSelectedRecord())).show();
	}

	/**
	 * 
	 */
	private void loadUsers() {
		dispatcher.execute(new FindAllUsersAction(),
				new AsyncCallback<CollectionResult<UserDto>>() {

					@Override
					public void onFailure(Throwable caught) {
						// SC.say(caught.toString());

					}

					@Override
					public void onSuccess(CollectionResult<UserDto> result) {
						fillGrid(result.getResult());
					}
				});
	}

	private void deleteUser() {
		dispatcher.execute(new DeleteUserAction(Long.parseLong(userGrid
				.getSelectedRecord().getAttribute(ID2))),
				new AsyncCallback<VoidResult>() {

					@Override
					public void onFailure(Throwable caught) {
						// SC.say(caught.toString());

					}

					@Override
					public void onSuccess(VoidResult res) {
						loadUsers();
						SC.say("Operacja zakonczona pomyslnie!");
					}
				});
	}

	private void fillGrid(List<UserDto> users) {
		userGrid.setData(new ListGridRecord[0]);
		for (UserDto usrDto : users) {
			ListGridRecord record = new ListGridRecord();
			record.setAttribute(ID2, String.valueOf(usrDto.getId()));
			record.setAttribute(NAME, usrDto.getName());
			record.setAttribute(SURNAME, usrDto.getSurename());
			record.setAttribute(LOGIN, usrDto.getLogin());
			record.setAttribute(PASSWORD, usrDto.getPassword());
			record.setAttribute(TYPE, String.valueOf(usrDto.getType()));
			userGrid.addData(record);
		}
	}

	/**
	 * 
	 */
	private void updateUsers() {
		dispatcher.execute(new UpdateUserAction(createModelFromTable()),
				new AsyncCallback<VoidResult>() {

					@Override
					public void onFailure(Throwable caught) {
						SC.say(caught.toString());

					}

					@Override
					public void onSuccess(VoidResult result) {
						SC.say("Edycja zakonczona sukcesem!");
					}
				});
	}

	// bleee
	private List<UserDto> createModelFromTable() {
		List<UserDto> users = new ArrayList<UserDto>();
		for (ListGridRecord record : userGrid.getRecords()) {
			users.add(createUserModel(record));
		}
		return users;
	}
	
	/**
	 * 
	 * @param record
	 * @return
	 */
	private UserDto createUserModel(ListGridRecord record) {
		UserDto dto = new UserDto();
		dto.setId(Integer.parseInt(record.getAttribute(ID2)));
		dto.setName(record.getAttribute(NAME));
		dto.setSurename(record.getAttribute(SURNAME));
		dto.setLogin(record.getAttribute(LOGIN));
		dto.setPassword(record.getAttribute(PASSWORD));
		dto.setType(Short.parseShort(record.getAttribute(TYPE)));
		return dto;
	}
}
